package com.xiangge.crawler;

import com.xiangge.config.CrawlerProperties;
import com.xiangge.crawler.inter.JsoupCrawlerBaseServiceAdaptor;
import com.xiangge.db.pojo.SynthesizeCategory;
import com.xiangge.db.pojo.SynthesizeGoods;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author lsy_server
 */
@Component
public class TianMaoCrawlerService extends JsoupCrawlerBaseServiceAdaptor {

    @Override
    public void setOpenFlag(Boolean openFlag) {
        super.setOpenFlag(true);
    }

    @Override
    public void crawler() {
        if (!openFlag) {
            return;
        }
        try {
            CrawlerProperties.CrawlerSource tianMao = properties.getTianMao();
            List<SynthesizeCategory> level1s = categoryRepository.findAllByLevel(0);
            level1s.parallelStream().flatMap(level -> categoryRepository.findAllByPid(level.getId()).parallelStream())
                    .forEach(
                            category -> {
                                if (category.getTianmaoInit()) {
                                    return;
                                }
                                for (int i = 1; i < PAGE_LIMIT; i = i + 2) {
                                    crawlerToDataBase(tianMao.getUrl(), i, category);
                                }
                                category.setTianmaoInit(true);
                                categoryRepository.save(category);
                            }
                    );
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void crawlerToDataBase(String url, int page, SynthesizeCategory category) {
        try {
            List<SynthesizeGoods> synthesizeGoods = crawlerGoods(url, page, category);
            goodsRepository.saveAll(synthesizeGoods);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<SynthesizeGoods> crawlerGoods(String crawlerUrl, Integer page, SynthesizeCategory id) {
        return null;
    }

    @Override
    public List<SynthesizeGoods> analyze(Document document, Integer categoryId) {
        return null;
    }
}
